package com.svm.math;

import java.awt.image.BufferedImage;

import com.svm.bean.Image;
import com.svm.operators.ImageResize;
import com.svm.util.SystemConfig;

public class EuclidianDistance {

	private Integer width;
	private Integer height;

	public EuclidianDistance() {
		width = SystemConfig.WIDTH;
		height = SystemConfig.HEIGHT;
	}

	public Double distance(Image imageQuery, Image imageBase) {

		Double distance = 0.;

		try {

			BufferedImage queryImage = ImageResize.resize(imageQuery.getPath(),
					width, height);
			BufferedImage baseImage = ImageResize.resize(imageBase.getPath(),
					width, height);

			Double[][] queryFeatures = getFeatures(queryImage);
			Double[][] baseFeatures = getFeatures(baseImage);

			distance = this.calculate(queryFeatures, baseFeatures);

		} catch (IllegalArgumentException ex) {
			System.out.println(ex);
		}

		return distance;
	}

	private Double calculate(Double[][] a, Double[][] b) {
		Double sum = 0.;

		for (int y = 0; y < width; y++) {
			for (int x = 0; x < height; x++) {
				sum += Math.pow((a[y][x] - b[y][x]), 2);
			}
		}

		return Math.sqrt(sum);
	}

	private Double[][] getFeatures(BufferedImage image) {
		// Color color;
		Double[][] vector = new Double[image.getHeight()][image.getWidth()];

		for (int y = 0; y < image.getHeight(); y++) {
			for (int x = 0; x < image.getWidth(); x++) {
				// color = new Color(image.getRGB(x, y));
				vector[y][x] = Double.parseDouble("" + image.getRGB(x, y) + "");// Double.parseDouble(""
																				// +
				// color.getRed() + "");
			}
		}

		return vector;
	}

}
